package com.nexgo.payment.pack;

import com.nexgo.common.ByteUtils;
import com.nexgo.data.entity.SendData;
import com.nexgo.data.entity.SendDataBuilder;
import com.nexgo.payment.constrant.PreferencesConstants;
import com.nexgo.payment.constrant.SysConstant;
import com.nexgo.payment.databases.DataSource;
import com.nexgo.payment.databases.SettleInfo;
import com.nexgo.payment.entity.TransData;
import com.nexgo.payment.util.MessageHelper;

/**
 * 批上送结束
 *
 * Created by xiaox on 2017/9/5.
 */
class BatchEndBuilder extends DataBuilder {
    BatchEndBuilder(TransData transData, DataSource repository) {
        super(transData, repository);
    }

    @Override
    SendData form() {
        SendData sendData = new SendDataBuilder().setListener(mListener).setSignListener(mSignListener).createSendData();
        sendData.setMsgType(mTransData.getTransType().getMsgType());
        sendData.setHeader(MessageHelper.formMessageHeader(mRepository.getParamValue(PreferencesConstants.TPDU)));
        sendData.setTraceNum(mRepository.getParamValue(PreferencesConstants.TRACE_NUMBER));
        mRepository.increaseTraceNumber();
        sendData.setTerminalId(mRepository.getParamValue(PreferencesConstants.TERMINAL_ID));
        sendData.setMerchantId(mRepository.getParamValue(PreferencesConstants.MERCHANT_ID));
        sendData.setAdditionalData(formAdditionalData());
        sendData.setField60(formField60());
        return sendData;
    }


    private String formAdditionalData() {
        return String.format(SysConstant.LOCALE, "%04d", mRepository.getBatchUploadSuccessfulTransRecordNum());
    }

    private String formField60() {
        StringBuilder sb = new StringBuilder();
        sb.append(mTransData.getTransType().getFuncCode());
        sb.append(mRepository.getParamValue(PreferencesConstants.BATCH_NUMBER));
        SettleInfo settleInfo = mRepository.getSettleInfo();
        sb.append(settleInfo.getIsEqu() && settleInfo.getIsInterEqu() ? "207" : "202");
        return ByteUtils.byteArray2HexString(sb.toString().getBytes());
    }

}
